<?php

namespace app\console\controller;

namespace app\console\controller;

use think\Session;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Ad as AdModel;
use app\console\model\Single as Model;
use app\common\trilateral\Classify as ClassifyAlias;
use think\Db;
use think\Debug;
class Single extends Controller
{


    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'clearCache' => ['only'],
    ];

    /**
     * 服务二级类以及金额  订单修改里
     */
    public function ajax2($id,$shop_id = 0,$order_id)
    {
//        $data = Db::name('single')
//            ->where('auding_status', 2)
//            ->where('is_delete', 1)
//            ->where('parent_id', $id)
//            ->select()->toArray();

        $data = Db::name('order_gift_count')
            ->alias('ogc')
            ->join('single s','ogc.single_content = s.id')
            ->where('order_id',$order_id)
            ->where('ogc.single_id',$id)
            ->where('ogc.gift_count','gt',0)
            ->select()->toArray();
        if(!empty($data)){
            foreach ($data as $k => &$v){
                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['id'])->value('person_price');
                $v['person_price'] = is_null($person_price) ? 0 :$person_price;
            }
        }else{
            $data[0]['cat_name'] = '';
            $data[0]['person_price'] = 0;
        }
        return $data;
    }

    public function ajax22($id,$shop_id,$gift_id){
        $data = Db::name('gift_count gc')
            ->where('gift_id',$gift_id)
            ->where('single_id',$id)
            ->join('single s','gc.single_content = s.id')
            ->select()->toArray();
        foreach ($data as $k => &$v){
            $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['single_content'])->value('person_price');
            $v['person_price'] = is_null($person_price) ? 0 :$person_price;
        }
        return $data;
    }

    /**
     * @param $id
     * @param int $shop_id
     * @return mixed 获得自己分类的金额
     */
    public function ajax4($id,$shop_id = 0)
    {
        $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$id)->value('person_price');
        return $person_price;
    }

    /**
     * @param $id
     * @param int $shop_id
     * @return array
     * 会员卡ajax
     */
    public function ajax2m($id,$shop_id = 0)
    {
        $data = Db::name('single')
            ->where('auding_status', 2)
            ->where('is_delete', 1)
            ->where('parent_id', $id)
            ->select()->toArray();

        if(!empty($data)){
            foreach ($data as $k => &$v){
                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['id'])->value('person_price');
                $v['person_price'] = is_null($person_price) ? 0 :$person_price;
            }
        }else{
            $data[0]['cat_name'] = '';
            $data[0]['person_price'] = 0;
        }
        return $data;
    }


    /**
     * 广告位列表
     */
    public function index()
    {

        Debug::remark('begin');

        $param = Request::instance()->param();

        $where = [];
        if(!empty($param)) $where['cat_name'] = ['like','%'.$param['title'].'%'];

        $data = Model::where($where)->order(['sort' => 'asc','id' => 'asc'])->select();//默认asc
       // halt($data);
        //$data = $this->array_sort($data,'sort');
        //$data = $this->array_sort($data,'sort','desc');
        $data = getMenuTree($data);
        //$data = $this->array_sort($data,'sort');
        Debug::remark('end');
        if(isset($param['export'])){
            $this->push($data);
        }

        //echo Debug::getRangeTime('begin','end').'s';
        return $this->fetch('', [
            'data' => $data,

        ]);
    }

    public function array_sort($arr, $keys, $type = 'asc')
    {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$keys];
        }
        if ($type == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

    public function push($data,$name = '服务类导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '科目代码')
            ->setCellValue('B1', '借贷方(绿色借方-灰色贷方)')
            ->setCellValue('C1', 'ID')
            ->setCellValue('D1', '标题')
            ->setCellValue('E1', '创建时间')
        ;
        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['code'])
                ->setCellValue('B' . $num, $v['dc_text'])
                ->setCellValue('C' . $num, $v['id'])
                ->setCellValue('D' . $num, str_repeat('--',$v['level']).$v['cat_name'])
                ->setCellValue('E' . $num, $v['create_time'])
            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('服务类导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    public function code(){
        $param = Request::instance()->param()['code'];

        if(!empty($param)){

            foreach ($param as $k => $v){

                $ret = Db::name('single')->where('id',$k)->setField('code',$v);
            }
            if($ret !== false){
                win('科目代码设置成功',Url::build('index'));
            }
        }

    }


    /**
     * 广告位创建
     */
    public function create(Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

//            // 验证
//            $validate = Loader::validate('AdType');
//            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }

        $news_type = Db::name('single')->where(['auding_status' => 2,'is_delete' => 1,'parent_id' => 0])->select();
        return $this->fetch('create', [
            "news_type" => $news_type,
        ]);

    }


    /**
     * 广告位编辑
     */
    public function update($id, Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            // 验证
           // $validate = Loader::validate('AdType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);


            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }

        $item = Model::get($id);
        $news_type = Db::name('single')->where(['auding_status' => 2,'is_delete' => 1,'parent_id' => 0])->select();
        return $this->fetch('create', [
            "news_type" => $news_type,
            'item' => $item
        ]);
    }



    /**
     * 广告位删除
     */
    public function destroy($id, Model $model)
    {

        if (Request::instance()->isGet()) {
            Db::name('single')->where('id',$id)->update(['delete_time' => date('Y-m-d H:i:s',time()),'is_delete' => 2,'delete_id' => session('manage_id')]);
            $title = Db::name('single')->where('id',$id)->find();
            Db::name('recycle_bin')->insert(['title' => $title['cat_name'],'type' =>'单页管理','table' => 'news','table_id' => $id,'delete_id' => Session::get('manage_id'),'delete_time' => date('Y-m-d H:i:s',time())]);
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }
    /**
     * 栏目状态改变
     */
    public function dc($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['dc' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 栏目全部删除
     */
    public function destroyAll($id, AdTypeModel $adType)
    {

        if ($adType->amputateAll($id)) {

            win('操作成功', Url::build('AdType/index'));
        }

        fail('操作失败');

    }





    /*
    * 排列顺序
    */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            Db::name('single')->where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('index'));
    }

    /**
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('AdType');
    }
}